//
//  accountUser.swift
//  SHWeibo2.0
//
//  Created by 黄礼潮 on 16/2/25.
//  Copyright © 2016年 黄礼潮. All rights reserved.
//

import UIKit

private let CZDictUserAccount = "CZDictUserAccount"
class UserAccount: NSObject {
    
   //创建用户单例
    static let shardUserAccount = UserAccount()
     /// 用于调用access_token，接口获取授权后的access token
    //用户登录信息
    var isLogin:Bool{
    
        return access_token != nil
    }
    var access_token: String?
    /// 当前授权用户的UID
    var uid: String?
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    var expiresDate:NSDate?
    
    var expires_in: NSTimeInterval = 0 {
    
        didSet{
        
         expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    
    }
  private override init() {
        super.init()
        loadUserAccount()
    }
    
//    init(dict:[String:AnyObject]) {
//        super.init()
//        
//        setValuesForKeysWithDictionary(dict)
//    }
    
    
   override func setValue(value: AnyObject?, forUndefinedKey key: String){}

//    //调试用的
    override  var description:String{
     //模型转字典
        let keys = ["access_token", "uid", "expires_in", "screen_name", "avatar_large","expiresDate"]
        
        return dictionaryWithValuesForKeys(keys).description
    
    }

}

extension UserAccount{
    //字典转模型 更新数据
    func updateUserAccount(dict:[String:AnyObject]){
    
       setValuesForKeysWithDictionary(dict)
        
       saveUserAccount()
    
    }
    //将用户信息保存到偏好设置中
    func saveUserAccount(){
    //模型转字典
      let keys = ["access_token", "uid", "expires_in", "screen_name", "avatar_large","expiresDate"]
    
      let dict = dictionaryWithValuesForKeys(keys)
    //保存到字典中
      NSUserDefaults.standardUserDefaults().setObject(dict, forKey: CZDictUserAccount)
      print(NSHomeDirectory())
    }
    
    //加载用户信息
    func loadUserAccount(){
    
        //从用户偏好设置中加载
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(CZDictUserAccount) as?[String:AnyObject] else{
        
            return
        }
        //字典转模型
        setValuesForKeysWithDictionary(dict)
        //判断是否过期
       //expiresDate = NSDate(timeIntervalSinceNow: 24 * 60 * 60)
        if isExpire{
          print("已经过期")
          access_token = nil
        
        }else{
         print("token 正常")
        }
    
    }
    private var isExpire:Bool{
       
        //NSDate() 现在的时间
       return expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending
    }


}
